package com.yupi.yuaicodemother.langGraph4j.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.yuaicodemother.langGraph4j.model.ImageResource;
import com.yupi.yuaicodemother.langGraph4j.model.enums.ImageCategoryEnum;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class UndrawIllustrationTool {

    private static final String UNDRAW_API_URL = "https://undraw.co/_next/data/N6M_hYvpIPjDtR8MHPCqU/search/%s.json?term=%s";
    private static final int TIMEOUT_MS = 30000; // 30秒超时
    private static final int MAX_RETRIES = 3; // 最大重试次数
    private static final int RETRY_DELAY_MS = 1000; // 重试延迟1秒

    @Tool("搜索插画图片，用于网站美化和装饰")
    public List<ImageResource> searchIllustrations(@P("搜索关键词") String query) {
        List<ImageResource> imageList = new ArrayList<>();
        int searchCount = 12;
        String apiUrl = String.format(UNDRAW_API_URL, query, query);

        // 带重试机制的请求
        for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
            try {
                log.debug("搜索插画，关键词: {}, 尝试次数: {}/{}", query, attempt, MAX_RETRIES);
                
                // 使用 try-with-resources 自动释放 HTTP 资源
                // 增加超时时间到30秒，并设置User-Agent避免被拒绝
                try (HttpResponse response = HttpRequest.get(apiUrl)
                        .timeout(TIMEOUT_MS)
                        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                        .execute()) {
                    
                    if (!response.isOk()) {
                        log.warn("搜索插画API返回非200状态码: {}, 关键词: {}", response.getStatus(), query);
                        return imageList;
                    }
                    
                    JSONObject result = JSONUtil.parseObj(response.body());
                    JSONObject pageProps = result.getJSONObject("pageProps");
                    if (pageProps == null) {
                        log.warn("搜索插画返回数据格式异常，pageProps为空，关键词: {}", query);
                        return imageList;
                    }
                    
                    JSONArray initialResults = pageProps.getJSONArray("initialResults");
                    if (initialResults == null || initialResults.isEmpty()) {
                        log.debug("搜索插画未找到结果，关键词: {}", query);
                        return imageList;
                    }
                    
                    int actualCount = Math.min(searchCount, initialResults.size());
                    for (int i = 0; i < actualCount; i++) {
                        JSONObject illustration = initialResults.getJSONObject(i);
                        String title = illustration.getStr("title", "插画");
                        String media = illustration.getStr("media", "");
                        if (StrUtil.isNotBlank(media)) {
                            imageList.add(ImageResource.builder()
                                    .category(ImageCategoryEnum.ILLUSTRATION)
                                    .description(title)
                                    .url(media)
                                    .build());
                        }
                    }
                    
                    log.info("搜索插画成功，关键词: {}, 找到 {} 张图片", query, imageList.size());
                    return imageList; // 成功则直接返回
                    
                }
            } catch (Exception e) {
                // 检查是否是超时异常（可能是 SocketTimeoutException 或被 HttpException 包装）
                boolean isTimeoutException = e instanceof SocketTimeoutException 
                        || (e instanceof HttpException && e.getCause() instanceof SocketTimeoutException)
                        || (e.getMessage() != null && e.getMessage().contains("Read timed out"));
                
                if (isTimeoutException) {
                    // 超时异常，需要重试
                    if (attempt < MAX_RETRIES) {
                        log.warn("搜索插画超时，关键词: {}, 尝试次数: {}/{}, {}ms后重试", 
                                query, attempt, MAX_RETRIES, RETRY_DELAY_MS);
                        try {
                            Thread.sleep(RETRY_DELAY_MS);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            log.error("重试延迟被中断", ie);
                            break;
                        }
                        continue; // 继续重试
                    } else {
                        // 最后一次尝试也失败了
                        log.error("搜索插画失败，已达到最大重试次数，关键词: {}", query, e);
                        // 不抛出异常，返回空列表，避免影响整个流程
                        break;
                    }
                } else {
                    // 非超时异常，不重试直接返回
                    log.error("搜索插画失败（非超时异常），关键词: {}", query, e);
                    break;
                }
            }
        }
        
        return imageList;
    }
}
